//
//  FLMHomeVC.m
//  FLMSuperS
//
//  Created by xiaoyang on 16/9/12.
//  Copyright © 2016年 FaLaoMiaoNetworkTechnologyCo. All rights reserved.
//

#import "FLMHomeVC.h"
#import "FLMSettingViewController.h"

#import "FLMMenuTableViewController.h"
#import "FLMDropdownMenu.h"

#import "FLMSearchBar.h"
#import "FLMDeatilViewController.h"

#import "SLable.h"
#import "FLMHomeView.h"
#import "FLMThreeJumpView.h"

#import "SDCycleScrollView.h"
#import "FLMHomeItemCell.h"

#import "FLMHomeHeaderView.h"
#import "FLMLoginVC.h"
#import "FLMHomeResponseModel.h"
#import "FLMWebViewController.h"
#import "FLMDeatilResponseModel.h"
@interface FLMHomeVC ()<FLMDropdownMenuDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) SDCycleScrollView      * lunboV; //轮播视图

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *indexlunboArr; //轮播数组

@property (nonatomic, strong) NSMutableArray *unionsModelArr; //快捷菜单模型数组

@property (nonatomic, strong) NSMutableArray *goodslistModelArr; //商品数组
/** 悬浮按钮 */
@property (nonatomic, strong) UIButton *btn;

/** 用来加载下一页数据的参数 */
@property (nonatomic, strong) NSString *page;
@end

@implementation FLMHomeVC

- (FLMDataType)type
{
    return 1;
}

//懒加载
- (NSMutableArray *)indexlunboArr
{
    if (!_indexlunboArr) {
        _indexlunboArr = [NSMutableArray array];
    }
    return _indexlunboArr;
}

//懒加载
- (NSMutableArray *)unionsModelArr
{
    if (!_unionsModelArr) {
        _unionsModelArr = [NSMutableArray array];
    }
    return _unionsModelArr;
}

//懒加载
- (NSMutableArray *)goodslistModelArr
{
    if (!_goodslistModelArr) {
        _goodslistModelArr = [NSMutableArray array];
    }
    return _goodslistModelArr;
}
- (void)viewWillAppear:(BOOL)animated
{
    [self loadShopData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
  
     //设置当有导航栏自动添加64的高度的属性为NO
    self.automaticallyAdjustsScrollViewInsets = NO;
    //设置一张空的图片
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
    //清除边框，设置一张空的图片
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    
    self.view.backgroundColor = [UIColor whiteColor];
    //设置导航栏内容
    [self setUpNavContent];
    //创建collectionView
    [self creatCollectionView];

    //设置刷新请求数据
    [self setUpRefresh];
}


#pragma mark --------------------
#pragma mark 刷新控件
- (void)setUpRefresh
{
    //header
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadShopData)];
    
    self.collectionView.mj_header.automaticallyChangeAlpha = YES;
   
    [self.collectionView.mj_header beginRefreshing];
    
    //footer
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreShopData)];

}


#pragma mark --------------------
#pragma mark 加载最新数据
- (void)loadShopData
{
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    NSString *useName = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
    NSString *passWord = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
//    if (useName.length <= 0 || passWord.length <= 0) {
//        FLMLoginVC *loginVC = [[FLMLoginVC alloc]init];
//        [self presentViewController:loginVC animated:YES completion:nil];
//        return;
//    }
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"uname"] = useName;
    parameters[@"upass"] = [BaseHttpRequest md5HexDigest:[NSString stringWithFormat:@"%@%@",passWord,@"sos_5941m"]];
    parameters[@"code"] = @"";
    parameters[@"token"] = @"f2c8ec76b30527be791752cab0cf743c";
    parameters[@"h"] = @"141";
    
    parameters[@"type"] = @(self.type);
    
    __weak typeof(self) weakSelf = self;
    [mgr POST:HomeURL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id responseObject) {
        
        FLMHomeResponseModel *model = [FLMHomeResponseModel mj_objectWithKeyValues:responseObject];
        
        weakSelf.goodslistModelArr = [model.msg.goodslist mutableCopy];
        weakSelf.unionsModelArr = [model.msg.unions mutableCopy];
        weakSelf.indexlunboArr = [model.msg.indexlunbo mutableCopy];
        
        //刷新表格
        [self.collectionView reloadData];
        
//        NSLog(@"%@---成功",responseObject);
        
        [self.collectionView.mj_header endRefreshing];
        
        //YCFAFNWriteToPlist(homePlist);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@---失败",error);
        
        if (error.code == NSURLErrorCancelled) {
           [XLsn0wHUD showTipText:@"无网络!" superview:self.view duration:1 animated:YES];
        }
    
        [self.collectionView.mj_header endRefreshing];
        
    }];
}

#pragma mark --------------------
#pragma mark 加载更多商品
- (void)loadMoreShopData
{

    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    NSString *useName = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
    NSString *passWord = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
    if (useName == nil || passWord== nil) {
        FLMLoginVC *loginVC = [[FLMLoginVC alloc]init];
        [self presentViewController:loginVC animated:YES completion:nil];
        return;
    }
    parameters[@"uname"] = useName;
    parameters[@"upass"] = [BaseHttpRequest md5HexDigest:[NSString stringWithFormat:@"%@%@",passWord,@"sos_5941m"]];
    parameters[@"code"] = @"";
    parameters[@"token"] = @"f2c8ec76b30527be791752cab0cf743c";
    parameters[@"h"] = @"141";
    
    parameters[@"page"] = self.page;
    parameters[@"type"] = @(self.type);
    
    __weak typeof(self) weakSelf = self;
    [mgr POST:HomeURL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id responseObject) {
        
        FLMHomeResponseModel *model = [FLMHomeResponseModel mj_objectWithKeyValues:responseObject];
        
        weakSelf.goodslistModelArr = [model.msg.goodslist mutableCopy];
        weakSelf.unionsModelArr = [model.msg.unions mutableCopy];
        weakSelf.indexlunboArr = [model.msg.indexlunbo mutableCopy];
    
        //拼接后面的数据
//        [_goodslistModelArr addObjectsFromArray:weakSelf.goodslistModelArr];
        
        self.goodslistModelArr = [model.msg.goodslist mutableCopy];
        
        //刷新表格
        [self.collectionView reloadData];
        
//        //服务器只有16条数据,一旦满16条就让它不再上拉刷新
//        if (_goodslistModelArr.count >= 16) {
//            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
//        }else{
//            [self.collectionView.mj_footer endRefreshing];
//        }
        
//        NSLog(@"%@---成功",responseObject);
        
        [self.collectionView.mj_footer endRefreshing];
        
        //YCFAFNWriteToPlist(homePlist);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //        NSLog(@"%@---失败",error);
        
        if (error.code == NSURLErrorCancelled) {
            [XLsn0wHUD showTipText:@"网路繁忙,请稍后再试!" superview:self.view duration:1 animated:YES];
        }
        
        [self.collectionView.mj_footer endRefreshing];
        
    }];

}

#pragma mark --------------------
#pragma mark 设置导航栏
- (void)setUpNavContent
{
    //设置导航栏上的左边item
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(presentLeftMenuViewController:) image:@"MainTagSubIcon" hightImage:@"MainTagSubIconClick"];
    //设置导航栏上的又边item
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(rightAddpPop:) image:@"tabbar_compose_background_icon_add" hightImage:@"tabbar_compose_background_icon_add"];
    
    //设置中间搜索框
    FLMSearchBar *searchBar = [FLMSearchBar searchBar];
    searchBar.width = 357;
    searchBar.height = 30;
    
    self.navigationItem.titleView = searchBar;
}



#pragma mark --------------------
#pragma mark 右边item
- (void)rightAddpPop:(UIButton *)titleButton
{
    //创建下拉菜单
    FLMDropdownMenu *menu = [FLMDropdownMenu menuWithType:FLMDropdownMenuRight];
    menu.delegate = self;
    menu.titles = @[@"签到",@"邀请",@"分享"].mutableCopy;
    
    [menu showAtPoint:CGPointMake(CGRectGetWidth(self.view.bounds) - kFLMDropdownMenuWidth, 64)];}

#pragma mark -- 设置collectionView-UI
- (void)creatCollectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.minimumInteritemSpacing = 5;
        layout.minimumLineSpacing = 5;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - 49) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[FLMHomeItemCell class] forCellWithReuseIdentifier:@"FLMHomeItemCell"];
        [_collectionView registerClass:[FLMHomeHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"FLMHomeHeaderView"];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_collectionView];
        
    }
}

#pragma mark - collectionView数据源
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    // 设置尾部控件的显示和隐藏
    self.collectionView.mj_footer.hidden = self.goodslistModelArr.count == 0;
    return self.goodslistModelArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //创建cell注册标识
    FLMHomeItemCell *cell = (FLMHomeItemCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"FLMHomeItemCell"forIndexPath:indexPath];
    
    //取出模型显示第几行数据
    [cell configueCellWithModel:self.goodslistModelArr[indexPath.row] indexPath:indexPath];
   
    return cell;
}


#pragma mark - UICollectionViewDelegate
#pragma mark --------------------
#pragma mark 跳转详情页
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    FLMGoodslistModel *detailModel = self.goodslistModelArr[indexPath.item];
    FLMDeatilViewController *detailVC = [[FLMDeatilViewController alloc] init];

    detailVC.num_iid = detailModel.num_iid;
    
    [detailVC setHidesBottomBarWhenPushed:YES];
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat itemWidth = (ScreenW - 15)/2;
    CGFloat itemHeight = itemWidth*4/3;
    return CGSizeMake(itemWidth, itemHeight);
}
/**
 *  设置分区代理数据
 */
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
    FLMHomeHeaderView *headerView =
    [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"FLMHomeHeaderView"
                                              forIndexPath:indexPath];
    //设置数据
    [headerView configBannarView:self.indexlunboArr menuArr:self.unionsModelArr];
    
    //点击菜单页回调
    [headerView setMuenClickBlock:^(FLMUnionsModel *unionsModel) {
        NSLog(@"FLMUnionsModel菜单菜单菜单%@",unionsModel.url);
        
        if (![unionsModel.url containsString:@"http"]) return;
        
        FLMWebViewController *webVc = [[FLMWebViewController alloc] init];
        
        //NSLog(@"%@", NSStringFromCGRect(webVc.view.bounds));
        
        webVc.url = [NSURL URLWithString:unionsModel.url];
        webVc.title = unionsModel.mall_name;
        
        //NSLog(@"进到哪个网站去了%@", webVc.url);
        
        
        [self.navigationController pushViewController:webVc animated:YES];
    }];
    
    //轮播回调
    [headerView setBannarClickBlock:^(NSString *bannarUrl) {
        
        if (![bannarUrl containsString:@"http"]) return;
        
        FLMWebViewController *webVc = [[FLMWebViewController alloc] init];
        webVc.url = [NSURL URLWithString:bannarUrl];
        
        //NSLog(@"进入地址是%@", webVc.url);
        [self.navigationController pushViewController:webVc animated:YES];
    }];
    
    return headerView;
    }
    return nil;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(ScreenW, [FLMHomeHeaderView getViewHeightWithMenuArr:self.unionsModelArr]);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 0, 5);
}


@end

